package de.karlNet.sambamanager.view.beans.forms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.LdapMemberOfTree;
import de.karlNet.sambamanager.ldapController.LdapMemberTree;
import de.karlNet.sambamanager.ldapController.commands.macros.ModifyGroupMacro;
import de.karlNet.sambamanager.ldapModel.LdapGroup;
import de.karlNet.sambamanager.ldapModel.dto.LdapGroupCreationDTO;
import de.karlNet.sambamanager.ldapModel.dto.LdapGroupModifyDTO;
import de.karlNet.sambamanager.view.beans.ManualLeafHandlingTreeNode;
import de.karlNet.sambamanager.view.beans.trees.LdapGroupBean;
import de.karlNet.sambamanager.view.beans.trees.LdapUserBean;

@Controller
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class EditGroupBean extends CreateGroupBean {
	@Autowired
	private LdapMemberOfTree ldapMemberOfTree;
	@Autowired
	private LdapMemberTree ldapMemberTree;
	@Autowired
	private LdapGroupBean ldapGroupBean;
	@Autowired
	private LdapUserBean ldapUserBean;
	@Autowired
	private ModifyGroupMacro modifyGroupMacro;

	@Override
	public void setShow(boolean show) {
		this.ldapGroupCreationDTO = new LdapGroupModifyDTO();
		this.ldapGroupCreationDTO
				.setLdapGroup((LdapGroup) this.nodeContainer.selectedNode
						.getLdapObject());
		((LdapGroupModifyDTO)this.ldapGroupCreationDTO).setOldGroup((LdapGroup) this.nodeContainer.selectedNode
						.getLdapObject());
		this.groupTree.reset();
		this.groupTree.setPreSelectedNodes(this.ldapMemberOfTree
				.getChildrenOfDN(this.ldapGroupCreationDTO.getLdapGroup()
						.getDn()));

		this.selectableUserGroupTree.reset();
		this.selectableUserGroupTree.setPreSelectedNodes(this.ldapMemberTree
				.getChildrenOfDN(this.getLdapGroup().getDn()));
		super.setShow(show);
	}

	@Override
	public String getPageName() {
		return "editGroupView";
	}

	@Override
	public String create() {
		try {
			this.ldapGroupCreationDTO.getMemberOf().addAll(
					this.groupTree.getSelectedGroups());
			this.ldapGroupCreationDTO.getMembers().addAll(
					this.selectableUserGroupTree.getSelectedUserGroups());

			this.modifyGroupMacro.modifyGroup((LdapGroupModifyDTO) ldapGroupCreationDTO);

			if (this.nodeContainer.selectedNode.isExpanded()) {
				new ManualLeafHandlingTreeNode("group",
						this.ldapGroupCreationDTO.getLdapGroup(),
						this.nodeContainer.selectedNode);
			}
			this.ldapGroupCreationDTO = new LdapGroupCreationDTO();
			this.ldapGroupBean.reset();
			this.ldapUserBean.reset();
			this.setShow(false);
			return "index.xhtml";
		} catch (Exception e) {
			this.showErrorMessage(e);
			return"";
		}
	}
}
